package com.example.littlepainter.home

import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavDirections
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.littlepainter.R
import com.example.littlepainter.data.PictureViewModel
import com.example.littlepainter.databinding.FragmentHomeBinding
import com.example.littlepainter.utils.TimeUtils
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream


class HomeFragment : Fragment() {
    private lateinit var binding:FragmentHomeBinding
    private val viewModel:PictureViewModel by activityViewModels()
    private val mAdapter = PictureAdapter()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //观察数据变化
        viewModel.models.observe(viewLifecycleOwner){
            mAdapter.setData(it)
        }

        //配置RecyclerView
        binding.recyclerView.apply {
            layoutManager = ScaleLayoutManager(requireContext())
            adapter = mAdapter
            PagerSnapHelper().attachToRecyclerView(this)
        }

        //add按钮点击事件
        binding.ivAdd.setOnClickListener {
            val action = HomeFragmentDirections.actionHomeFragmentToDrawFragment(null)
            findNavController().navigate(action)
        }

        binding.ivDelete.setOnClickListener {
            val lm = binding.recyclerView.layoutManager as LinearLayoutManager
            val index = lm.findFirstCompletelyVisibleItemPosition()
            viewModel.deletePicture(index)
        }

        binding.ivShare.setOnClickListener {
            val lm = binding.recyclerView.layoutManager as LinearLayoutManager
            val index = lm.findFirstCompletelyVisibleItemPosition()
            val picture = viewModel.models.value!![index]
            share(picture.url)
        }

        binding.ivDown.setOnClickListener {
            val lm = binding.recyclerView.layoutManager as LinearLayoutManager
            val index = lm.findFirstCompletelyVisibleItemPosition()
            val picture = viewModel.models.value!![index]
            download(picture.url)
        }
    }

    private var mUri:Uri? = null
    fun download(filePath: String){
        val file = File(filePath)
        if (!file.exists()) return

        //找到相册对应uri地址
        val uri = if (VERSION.SDK_INT > VERSION_CODES.Q) {
            MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        }else{
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        }

        //将当前的图片地址配置一下
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME,TimeUtils.timeName())
            put(MediaStore.Images.Media.MIME_TYPE,"image/jpeg")
        }
        //图片在相册里面的具体uri
        val imageUri = requireActivity().contentResolver.insert(uri,contentValues)

        if (VERSION.SDK_INT >VERSION_CODES.R) {
            MediaStore.createWriteRequest(requireActivity().contentResolver, listOf(imageUri))
        }
        //输出流
        requireContext().contentResolver.openOutputStream(imageUri!!).use { os ->
            BufferedInputStream(FileInputStream(file)).use { bis ->
                val bufferArray = ByteArray(1024)
                var len = bis.read(bufferArray,0,1024)
                while (len > 0){
                    os!!.write(bufferArray,0,len)
                    len = bis.read(bufferArray,0,1024)
                }
                os!!.flush()
                Toast.makeText(requireContext(),"保存成功",Toast.LENGTH_LONG).show()
                mUri = imageUri
            }
        }
    }

    fun share(filePath:String){
        val file = File(filePath)
        if (!file.exists()) return

        //filePath  -> FileProvider ->
        val uri = FileProvider.getUriForFile(
            requireContext(),
            "com.example.littlepainter.fileprovider",
            file
        )

        val intent = Intent(Intent.ACTION_SEND)
        intent.putExtra(Intent.EXTRA_STREAM,uri)
        intent.type = "image/jpeg"
        startActivity(Intent.createChooser(intent,"图片分享"))
    }
}








